package summer.codegenerator.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import summer.codegenerator.model.Entity;
import summer.codegenerator.model.EntityAttribute;
import summer.codegenerator.model.base.ModelUtils;
import summer.codegenerator.persistence.hibernate.EntityAttributeDao;
import summer.codegenerator.persistence.hibernate.base.BaseDao;
import summer.codegenerator.persistence.hibernate.base.tool.Condition;
import summer.codegenerator.service.base.BaseServiceImpl;

import java.util.List;
import java.util.Set;
import java.util.jar.Attributes;

@Service
public class EntityServiceImpl extends BaseServiceImpl<Entity> implements EntityService {

    @Override
    @Autowired
    public void setBaseDao(BaseDao<Entity> baseDao) {
        this.baseDao = baseDao;
    }

    @Autowired
    private EntityAttributeDao eaDao;

    @Override
    public Entity save(Entity entity) throws Exception {
        // 子表
        List<EntityAttribute> eas = entity.getAttributes();
        // 保存主表
        baseDao.save(entity);
        // 保存子表
        for(EntityAttribute ea : eas) {
            ea.setAttachedEntity(entity);
            eaDao.save(ea);
        }
        return baseDao.copyById(entity.getEntityId());
    }

    @Override
    public Entity update(Entity entity) throws Exception {
        // 子表
        List<EntityAttribute> eas = entity.getAttributes();
        // 保存主表
        baseDao.update(entity);
        // 保存子表
        for(EntityAttribute ea : eas) {
            if (ea.getEntityAttributeId() == null) {
                ea.setAttachedEntity(entity);
                eaDao.save(ea);
            } else {
                eaDao.update(ea);
            }
        }
        // 已持久化对象Ids
        Set<Long> persistedIds = ModelUtils.ids(
                eaDao.list(new Condition("attachedEntity", "=", entity, "attachedEntity"), null));
        // 幸存者对象Ids
        Set<Long> survivorIds = ModelUtils.ids(eas);
        // 删除不在幸存者里的对象
        for(Long persistedId : persistedIds) {
            if(!survivorIds.contains(persistedId)) {
                eaDao.delete(persistedId);
            }
        }
        return baseDao.copyById(entity.getEntityId());
    }
}
